import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import '../../models/post_type.dart';
import '../../models/category_model.dart';
import '../../services/api_service.dart';
import '../../widgets/upload_selector.dart';
import '../home/home_page.dart';

/// 发表动态页面 V2
/// 使用优化的上传组件
class PublishPostPageV2 extends StatefulWidget {
  const PublishPostPageV2({super.key});

  @override
  State<PublishPostPageV2> createState() => _PublishPostPageV2State();
}

class _PublishPostPageV2State extends State<PublishPostPageV2> {
  // 动态类型
  PostType _selectedPostType = PostType.text;
  
  // 表单控制器
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  final _summaryController = TextEditingController();
  
  // 服务商品相关控制器
  final _serviceNameController = TextEditingController();
  final _serviceDescriptionController = TextEditingController();
  final _servicePriceController = TextEditingController();
  final _serviceDiscountController = TextEditingController();
  
  // 数据
  String? _coverImageUrl;
  List<String> _imageUrls = [];
  List<VideoItem> _videoItems = [];
  List<Category> _categories = [];
  Category? _selectedCategory;
  bool _isOriginal = true;
  bool _isPublishing = false;

  @override
  void initState() {
    super.initState();
    _loadCategories();
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _summaryController.dispose();
    _serviceNameController.dispose();
    _serviceDescriptionController.dispose();
    _servicePriceController.dispose();
    _serviceDiscountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发表动态'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 动态类型选择
                  _buildPostTypeSelector(),
                  const SizedBox(height: 24),
                  
                  // 分类选择
                  _buildCategorySelector(),
                  const SizedBox(height: 24),
                  
                  // 原创标识
                  _buildOriginalToggle(),
                  const SizedBox(height: 24),
                  
                  // 根据类型显示不同内容
                  _buildContentByType(),
                  
                  // 底部间距，避免被按钮遮挡
                  const SizedBox(height: 100),
                ],
              ),
            ),
          ),
          // 底部发布按钮
          _buildBottomPublishButton(),
        ],
      ),
    );
  }

  /// 构建动态类型选择器
  Widget _buildPostTypeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择动态类型',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: PostType.values.map((type) {
            final isSelected = _selectedPostType == type;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedPostType = type;
                  _clearContent();
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(
                    color: isSelected ? Colors.blue : Colors.grey.shade300,
                    width: 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      _getPostTypeIcon(type),
                      color: isSelected ? Colors.blue : Colors.grey.shade600,
                      size: 16,
                    ),
                    const SizedBox(width: 6),
                    Text(
                      type.name,
                      style: TextStyle(
                        color: isSelected ? Colors.blue : Colors.grey.shade700,
                        fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建分类选择器
  Widget _buildCategorySelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择分类',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: _categories.map((category) {
            final isSelected = _selectedCategory?.id == category.id;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedCategory = category;
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(
                    color: isSelected ? Colors.blue : Colors.grey.shade300,
                    width: 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      isSelected ? Icons.check_circle : Icons.radio_button_unchecked,
                      color: isSelected ? Colors.blue : Colors.grey.shade600,
                      size: 16,
                    ),
                    const SizedBox(width: 6),
                    Text(
                      category.name,
                      style: TextStyle(
                        color: isSelected ? Colors.blue : Colors.grey.shade700,
                        fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建原创标识切换
  Widget _buildOriginalToggle() {
    return Row(
      children: [
        Checkbox(
          value: _isOriginal,
          onChanged: (value) {
            setState(() {
              _isOriginal = value ?? true;
            });
          },
        ),
        const Text('原创内容'),
        const Spacer(),
        Text(
          _isOriginal ? '原创' : '转载',
          style: TextStyle(
            color: _isOriginal ? Colors.green : Colors.orange,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  /// 构建底部发布按钮
  Widget _buildBottomPublishButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: ElevatedButton(
            onPressed: _isPublishing ? null : _showPublishConfirmDialog,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              elevation: 2,
            ),
            child: _isPublishing
                ? const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ),
                      SizedBox(width: 12),
                      Text('发布中...'),
                    ],
                  )
                : const Text(
                    '发布动态',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
          ),
        ),
      ),
    );
  }

  /// 根据类型构建内容
  Widget _buildContentByType() {
    switch (_selectedPostType) {
      case PostType.text:
        return _buildTextContent();
      case PostType.article:
        return _buildArticleContent();
      case PostType.video:
        return _buildVideoContent();
      case PostType.videoCollection:
        return _buildVideoCollectionContent();
      case PostType.service:
        return _buildServiceContent();
    }
  }

  /// 构建图文内容
  Widget _buildTextContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleInput(),
        const SizedBox(height: 16),
        _buildContentInput(),
        const SizedBox(height: 16),
        _buildImageUpload(),
      ],
    );
  }

  /// 构建图片内容
  Widget _buildImageContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleInput(),
        const SizedBox(height: 16),
        _buildImageUpload(),
        const SizedBox(height: 16),
        _buildContentInput(),
      ],
    );
  }

  /// 构建文章内容
  Widget _buildArticleContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleInput(),
        const SizedBox(height: 16),
        _buildCoverImageUpload(),
        const SizedBox(height: 16),
        _buildContentInput(),
      ],
    );
  }

  /// 构建视频内容
  Widget _buildVideoContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleInput(),
        const SizedBox(height: 16),
        _buildVideoUpload(),
        const SizedBox(height: 16),
        _buildContentInput(),
      ],
    );
  }

  /// 构建视频集合内容
  Widget _buildVideoCollectionContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleInput(),
        const SizedBox(height: 16),
        _buildSummaryInput(),
        const SizedBox(height: 16),
        _buildCoverImageUpload(),
        const SizedBox(height: 16),
        _buildVideoCollectionUpload(),
      ],
    );
  }

  /// 构建服务商品内容
  Widget _buildServiceContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildServiceNameInput(),
        const SizedBox(height: 16),
        _buildServiceDescriptionInput(),
        const SizedBox(height: 16),
        _buildServicePriceInput(),
        const SizedBox(height: 16),
        _buildServiceDiscountInput(),
        const SizedBox(height: 16),
        _buildCoverImageUpload(),
      ],
    );
  }

  /// 构建标题输入
  Widget _buildTitleInput() {
    return TextField(
      controller: _titleController,
      decoration: const InputDecoration(
        labelText: '标题',
        border: OutlineInputBorder(),
        hintText: '请输入标题',
      ),
      maxLength: 100,
    );
  }

  /// 构建内容输入
  Widget _buildContentInput() {
    return TextField(
      controller: _contentController,
      decoration: const InputDecoration(
        labelText: '内容',
        border: OutlineInputBorder(),
        hintText: '请输入内容',
      ),
      maxLines: 5,
      maxLength: 1000,
    );
  }

  /// 构建摘要输入
  Widget _buildSummaryInput() {
    return TextField(
      controller: _summaryController,
      decoration: const InputDecoration(
        labelText: '摘要',
        border: OutlineInputBorder(),
        hintText: '请输入摘要',
      ),
      maxLines: 3,
      maxLength: 200,
    );
  }

  /// 构建服务名称输入
  Widget _buildServiceNameInput() {
    return TextField(
      controller: _serviceNameController,
      decoration: const InputDecoration(
        labelText: '服务名称',
        border: OutlineInputBorder(),
        hintText: '请输入服务名称',
      ),
      maxLength: 50,
    );
  }

  /// 构建服务描述输入
  Widget _buildServiceDescriptionInput() {
    return TextField(
      controller: _serviceDescriptionController,
      decoration: const InputDecoration(
        labelText: '服务描述',
        border: OutlineInputBorder(),
        hintText: '请输入服务描述',
      ),
      maxLines: 3,
      maxLength: 500,
    );
  }

  /// 构建服务价格输入
  Widget _buildServicePriceInput() {
    return TextField(
      controller: _servicePriceController,
      decoration: const InputDecoration(
        labelText: '价格',
        border: OutlineInputBorder(),
        hintText: '请输入价格',
        suffixText: '元',
      ),
      keyboardType: TextInputType.number,
    );
  }

  /// 构建服务折扣输入
  Widget _buildServiceDiscountInput() {
    return TextField(
      controller: _serviceDiscountController,
      decoration: const InputDecoration(
        labelText: '折扣',
        border: OutlineInputBorder(),
        hintText: '请输入折扣',
        suffixText: '折',
      ),
      keyboardType: TextInputType.number,
    );
  }

  /// 构建图片上传
  Widget _buildImageUpload() {
    return UploadSelector(
      urls: _imageUrls,
      onUrlsChanged: (urls) {
        setState(() {
          _imageUrls = urls;
        });
      },
      uploadType: UploadType.image,
      maxCount: 9,
      itemSize: 120.0,
      showPreview: true,
    );
  }

  /// 构建封面图片上传
  Widget _buildCoverImageUpload() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '封面图片',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        UploadSelector(
          urls: _coverImageUrl != null ? [_coverImageUrl!] : [],
          onUrlsChanged: (urls) {
            setState(() {
              _coverImageUrl = urls.isNotEmpty ? urls.first : null;
            });
          },
          uploadType: UploadType.image,
          maxCount: 1,
          itemSize: 200.0,
          showPreview: true,
        ),
      ],
    );
  }

  /// 构建视频上传
  Widget _buildVideoUpload() {
    return UploadSelector(
      urls: _videoItems.map((video) => video.url).toList(),
      onUrlsChanged: (urls) {
        setState(() {
          _videoItems = urls.map((url) => VideoItem(
            title: '视频',
            url: url,
            coverUrl: null,
          )).toList();
        });
      },
      uploadType: UploadType.video,
      maxCount: 1,
      itemSize: 200.0,
      showPreview: false,
    );
  }

  /// 构建视频集合上传
  Widget _buildVideoCollectionUpload() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              '视频列表',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            TextButton.icon(
              onPressed: _addVideo,
              icon: const Icon(Icons.add),
              label: const Text('添加视频'),
            ),
          ],
        ),
        const SizedBox(height: 8),
        if (_videoItems.isEmpty)
          Container(
            width: double.infinity,
            height: 120,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade300),
              borderRadius: BorderRadius.circular(12),
              color: Colors.grey.shade50,
            ),
            child: const Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.video_library, size: 32, color: Colors.grey),
                SizedBox(height: 8),
                Text('点击添加视频', style: TextStyle(color: Colors.grey)),
              ],
            ),
          )
        else
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _videoItems.length,
            itemBuilder: (context, index) {
              final video = _videoItems[index];
              return Container(
                margin: const EdgeInsets.only(bottom: 12),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    Icon(Icons.video_file, color: Colors.blue),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(video.title, style: const TextStyle(fontWeight: FontWeight.w500)),
                          Text(video.url, style: TextStyle(color: Colors.grey.shade600, fontSize: 12)),
                        ],
                      ),
                    ),
                    IconButton(
                      onPressed: () {
                        setState(() {
                          _videoItems.removeAt(index);
                        });
                      },
                      icon: const Icon(Icons.delete, color: Colors.red),
                    ),
                  ],
                ),
              );
            },
          ),
      ],
    );
  }

  /// 获取动态类型图标
  IconData _getPostTypeIcon(PostType type) {
    switch (type) {
      case PostType.text:
        return Icons.text_fields;
      case PostType.article:
        return Icons.article;
      case PostType.video:
        return Icons.videocam;
      case PostType.videoCollection:
        return Icons.video_library;
      case PostType.service:
        return Icons.shopping_cart;
    }
  }

  /// 清空内容
  void _clearContent() {
    _titleController.clear();
    _contentController.clear();
    _summaryController.clear();
    _serviceNameController.clear();
    _serviceDescriptionController.clear();
    _servicePriceController.clear();
    _serviceDiscountController.clear();
    _coverImageUrl = null;
    _imageUrls.clear();
    _videoItems.clear();
  }

  /// 加载分类
  Future<void> _loadCategories() async {
    // 暂时使用默认分类，等服务器接口准备好后再从服务器获取
    setState(() {
      _categories = [
        Category(id: '1', name: '科技'),
        Category(id: '2', name: '文娱'),
        Category(id: '3', name: '游戏'),
        Category(id: '4', name: '旅行'),
        Category(id: '5', name: '美食'),
        Category(id: '6', name: '运动'),
        Category(id: '7', name: '教育'),
        Category(id: '8', name: '其他'),
      ];
      _selectedCategory = _categories.first;
    });
    
    // TODO: 等服务器接口准备好后，取消注释下面的代码
    /*
    try {
      final categoriesData = await ApiService().getContentCategories();
      final categories = categoriesData.map((item) => Category.fromJson(item)).toList();
      setState(() {
        _categories = categories;
        if (categories.isNotEmpty) {
          _selectedCategory = categories.first;
        }
      });
    } catch (e) {
      // 使用默认分类
      setState(() {
        _categories = [
          Category(id: '1', name: '默认分类'),
        ];
        _selectedCategory = _categories.first;
      });
    }
    */
  }

  /// 添加视频
  void _addVideo() {
    showDialog(
      context: context,
      builder: (context) => _VideoAddDialog(
        onAdd: (video) {
          setState(() {
            _videoItems.add(video);
          });
        },
      ),
    );
  }

  /// 显示发布确认对话框
  void _showPublishConfirmDialog() {
    if (!_validateForm()) return;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认发布'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('动态类型：${_selectedPostType.name}'),
            const SizedBox(height: 8),
            Text('分类：${_selectedCategory?.name ?? '未选择'}'),
            const SizedBox(height: 8),
            Text('内容类型：${_isOriginal ? '原创' : '转载'}'),
            if (_titleController.text.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text('标题：${_titleController.text}'),
            ],
            if (_imageUrls.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text('图片数量：${_imageUrls.length}'),
            ],
            if (_videoItems.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text('视频数量：${_videoItems.length}'),
            ],
            const SizedBox(height: 16),
            const Text(
              '确定要发布这条动态吗？',
              style: TextStyle(fontWeight: FontWeight.w500),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _publishPost();
            },
            child: const Text('确认发布'),
          ),
        ],
      ),
    );
  }

  /// 发布动态
  Future<void> _publishPost() async {
    setState(() {
      _isPublishing = true;
    });

    try {
      final postData = _preparePostData();
      await ApiService().publishPost(postData);
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('发布成功')),
        );
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const HomePage()),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('发布失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isPublishing = false;
        });
      }
    }
  }

  /// 验证表单
  bool _validateForm() {
    if (_selectedCategory == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择分类')),
      );
      return false;
    }

    switch (_selectedPostType) {
      case PostType.text:
        if (_titleController.text.trim().isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请输入标题')),
          );
          return false;
        }
        break;
      case PostType.article:
        if (_titleController.text.trim().isEmpty || _contentController.text.trim().isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请输入标题和内容')),
          );
          return false;
        }
        break;
      case PostType.video:
        if (_videoItems.isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请添加视频')),
          );
          return false;
        }
        break;
      case PostType.videoCollection:
        if (_videoItems.length < 2) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('视频集合至少需要2个视频')),
          );
          return false;
        }
        break;
      case PostType.service:
        if (_serviceNameController.text.trim().isEmpty || 
            _serviceDescriptionController.text.trim().isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请填写服务名称和描述')),
          );
          return false;
        }
        break;
    }

    return true;
  }

  /// 准备发布数据
  Map<String, dynamic> _preparePostData() {
    Map<String, dynamic> data = {
      'postType': _selectedPostType.dbValue,
      'categoryId': _selectedCategory!.id,
      'categoryName': _selectedCategory!.name,
      'isOriginal': _isOriginal,
    };

    switch (_selectedPostType) {
      case PostType.text:
        data.addAll({
          'title': _titleController.text.trim(),
          'content': _contentController.text.trim(),
          'images': _imageUrls,
        });
        break;
      case PostType.article:
        data.addAll({
          'title': _titleController.text.trim(),
          'content': _contentController.text.trim(),
          'coverUrl': _coverImageUrl,
        });
        break;
      case PostType.video:
        data.addAll({
          'title': _titleController.text.trim(),
          'content': _contentController.text.trim(),
          'videos': _videoItems.map((video) => {
            'title': video.title,
            'url': video.url,
            'coverUrl': video.coverUrl,
          }).toList(),
        });
        break;
      case PostType.videoCollection:
        data.addAll({
          'title': _titleController.text.trim(),
          'summary': _summaryController.text.trim(),
          'coverUrl': _coverImageUrl,
          'videos': _videoItems.map((video) => {
            'title': video.title,
            'url': video.url,
            'coverUrl': video.coverUrl,
          }).toList(),
        });
        break;
      case PostType.service:
        data.addAll({
          'title': _serviceNameController.text.trim(),
          'content': _serviceDescriptionController.text.trim(),
          'coverUrl': _coverImageUrl,
          'serviceProduct': {
            'title': _serviceNameController.text.trim(),
            'description': _serviceDescriptionController.text.trim(),
            'price': double.tryParse(_servicePriceController.text) ?? 0.0,
            'discount': double.tryParse(_serviceDiscountController.text) ?? 0.0,
          },
        });
        break;
    }

    return data;
  }
}

/// 视频项目模型
class VideoItem {
  final String title;
  final String url;
  final String? coverUrl;
  final int? durationSec;

  VideoItem({
    required this.title,
    required this.url,
    this.coverUrl,
    this.durationSec,
  });
}

/// 添加视频对话框
class _VideoAddDialog extends StatefulWidget {
  final Function(VideoItem) onAdd;

  const _VideoAddDialog({required this.onAdd});

  @override
  State<_VideoAddDialog> createState() => _VideoAddDialogState();
}

class _VideoAddDialogState extends State<_VideoAddDialog> {
  final _titleController = TextEditingController();
  final _urlController = TextEditingController();
  String? _coverUrl;
  File? _videoFile;
  bool _isUploading = false;

  @override
  void dispose() {
    _titleController.dispose();
    _urlController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加视频'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            controller: _titleController,
            decoration: const InputDecoration(
              labelText: '视频标题',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16),
          // 视频文件选择区域
          _buildVideoFileSelector(),
          const SizedBox(height: 16),
          // 或者手动输入URL
          TextField(
            controller: _urlController,
            decoration: const InputDecoration(
              labelText: '视频URL（可选，如果已选择文件则自动填充）',
              border: OutlineInputBorder(),
            ),
            enabled: _videoFile == null,
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _isUploading ? null : _handleAddVideo,
          child: _isUploading 
            ? const SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
            : const Text('添加'),
        ),
      ],
    );
  }

  /// 构建视频文件选择器
  Widget _buildVideoFileSelector() {
    return Container(
      width: double.infinity,
      height: 120,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(8),
        color: _videoFile != null ? Colors.green.shade50 : Colors.grey.shade50,
      ),
      child: _videoFile != null
          ? _buildVideoFileInfo()
          : _buildVideoFilePicker(),
    );
  }

  /// 构建视频文件信息显示
  Widget _buildVideoFileInfo() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.video_file, color: Colors.green.shade600),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  _videoFile!.path.split('/').last,
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    color: Colors.green.shade700,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              IconButton(
                onPressed: () {
                  setState(() {
                    _videoFile = null;
                    _urlController.clear();
                  });
                },
                icon: const Icon(Icons.close, color: Colors.red),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            '文件大小: ${(_videoFile!.lengthSync() / 1024 / 1024).toStringAsFixed(2)} MB',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade600,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建视频文件选择按钮
  Widget _buildVideoFilePicker() {
    return InkWell(
      onTap: _pickVideoFile,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.video_library_outlined,
            size: 40,
            color: Colors.grey.shade600,
          ),
          const SizedBox(height: 8),
          Text(
            '选择视频文件',
            style: TextStyle(
              color: Colors.grey.shade600,
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            '支持 MP4, MOV, AVI 等格式',
            style: TextStyle(
              color: Colors.grey.shade500,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 选择视频文件
  Future<void> _pickVideoFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.video,
        allowMultiple: false,
      );

      if (result != null && result.files.single.path != null) {
        setState(() {
          _videoFile = File(result.files.single.path!);
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择视频文件失败: $e')),
        );
      }
    }
  }

  /// 处理添加视频
  Future<void> _handleAddVideo() async {
    if (_titleController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入视频标题')),
      );
      return;
    }

    if (_videoFile == null && _urlController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择视频文件或输入视频URL')),
      );
      return;
    }

    setState(() {
      _isUploading = true;
    });

    try {
      String videoUrl = _urlController.text.trim();
      
      // 如果选择了文件，先上传文件
      if (_videoFile != null) {
        videoUrl = await _uploadVideoFile(_videoFile!);
      }

      widget.onAdd(VideoItem(
        title: _titleController.text.trim(),
        url: videoUrl,
        coverUrl: _coverUrl,
      ));

      if (mounted) {
        Navigator.pop(context);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('添加视频失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isUploading = false;
        });
      }
    }
  }

  /// 上传视频文件
  Future<String> _uploadVideoFile(File videoFile) async {
    try {
      final result = await ApiService().uploadVideo(videoFile);
      return result['data'];
    } catch (e) {
      throw Exception('视频上传失败: $e');
    }
  }
}
